package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.Year;
import com.itheima.domain.vo.AnalysisSummaryVo;
import com.itheima.domain.vo.AnalysisUserVo;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private LogMapper logMapper;//查询日志表

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    /**
     * 目的 将日志表记录查询出来放入分析表
     * 每一天的第一次执行会新增 后续执行会修改
     */
    @Override
    public void saveOrUpdate() {
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //第二次访问 先查询看数据库是否有数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_date" , today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);

        if(analysisByDay == null){
            //第一次访问代码
            analysisByDay = new AnalysisByDay();
            //封装对象
            analysisByDay.setRecordDate(new Date()); // 统计日期
            Integer numRegistered = logMapper.findNumRegistered("0102" , today);
            analysisByDay.setNumRegistered(numRegistered);// 新注册的用户数
            Integer numLogin = logMapper.findNumRegistered("0101" , today);
            analysisByDay.setNumLogin(numLogin);//登录次数
            Integer numActive = logMapper.findNumActive(today);
            analysisByDay.setNumActive(numActive);//活跃用户数
            Integer numRetention1d =logMapper.findAumRetention1d(yesterday , today);
            analysisByDay.setNumRetention1d(numRetention1d);//次日留存用户数
            analysisByDayMapper.insert(analysisByDay);
        }else{
            //后续的访问
            //封装对象
            analysisByDay.setRecordDate(new Date()); // 统计日期
            Integer numRegistered = logMapper.findNumRegistered("0102" , today);
            analysisByDay.setNumRegistered(numRegistered);// 新注册的用户数
            Integer numLogin = logMapper.findNumRegistered("0101" , today);
            analysisByDay.setNumLogin(numLogin);//登录次数
            Integer numActive = logMapper.findNumActive(today);
            analysisByDay.setNumActive(numActive);//活跃用户数
            Integer numRetention1d =logMapper.findAumRetention1d(yesterday , today);
            analysisByDay.setNumRetention1d(numRetention1d);//次日留存用户数
            analysisByDayMapper.updateById(analysisByDay);
        }


    }

    /**
     * 封装九个参数 概要统计
     * @return
     */
    @Override
    public AnalysisSummaryVo summary() {

        //查询昨天和今天的记录
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //今日数据
        QueryWrapper todayWrapper= new  QueryWrapper();
        todayWrapper.eq("record_date" , today);
        AnalysisByDay todayData = analysisByDayMapper.selectOne(todayWrapper);

        //昨日数据
        QueryWrapper yesterdayWrapper= new  QueryWrapper();
        yesterdayWrapper.eq("record_date" , yesterday);
        AnalysisByDay yesterdayData = analysisByDayMapper.selectOne(yesterdayWrapper);


        Long cumulativeUsers = analysisByDayMapper.findCumulativeUsers();//累计用户数


        String monthDay = DateUtil.offsetDay(new Date(), -30).toDateStr();
        String weekDay = DateUtil.offsetDay(new Date(), -7).toDateStr();
        Long activePassMonth = analysisByDayMapper.findActivePassByTime(monthDay , today);//过去三十天活跃用户数
        Long activePassWeek = analysisByDayMapper.findActivePassByTime(weekDay,today);//过去七天活跃用户数
        //封装对象
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        vo.setCumulativeUsers(cumulativeUsers);//累计用户数
        vo.setActivePassMonth(activePassMonth);//过去三十天活跃用户数
        vo.setActivePassWeek(activePassWeek);//过去七天活跃用户数

        vo.setNewUsersToday(todayData.getNumRegistered().longValue());//今日新增用户数量
        BigDecimal bigDecimal = ComputeUtil.computeRate(todayData.getNumRegistered(), yesterdayData.getNumRegistered());
        vo.setNewUsersTodayRate(bigDecimal);//今日新增用户涨跌率

        vo.setLoginTimesToday(todayData.getNumLogin().longValue());//今日登录次数
        BigDecimal bigDecimal2 = ComputeUtil.computeRate(todayData.getNumLogin(), yesterdayData.getNumLogin());
        vo.setLoginTimesTodayRate(bigDecimal2);//今日登录次数涨跌率

        vo.setActiveUsersToday(todayData.getNumActive().longValue());//今日活跃用户数量
        BigDecimal bigDecimal3 = ComputeUtil.computeRate(todayData.getNumActive(), yesterdayData.getNumActive());
        vo.setActiveUsersTodayRate(bigDecimal3);//今日活跃用户涨跌率
        return vo;
    }

    //统计图
    @Override
    public AnalysisUserVo users(String start, String end, String type) {
        //今年开始时间
        String thisStart = DateUtil.offsetDay(new Date(Long.valueOf(start)), 0).toDateStr();
        //今年结束时间
        String thisEnd = DateUtil.offsetDay(new Date(Long.valueOf(end)), 0).toDateStr();
        //去年开始时间
        String lastStart = DateUtil.offset(new Date(Long.valueOf(start)), DateField.YEAR, -1).toDateStr();
        //去年结束时间
        String lastEnd = DateUtil.offset(new Date(Long.valueOf(end)), DateField.YEAR, -1).toDateStr();

        //调用封装的方法
        List thisYear = analysisByDay(thisStart, thisEnd, type);
        List lastYear = analysisByDay(lastStart, lastEnd, type);

        //封装返回值
        AnalysisUserVo analysisUserVo = new AnalysisUserVo();
        analysisUserVo.setThisYear(thisYear);
        analysisUserVo.setLastYear(lastYear);

        //返回
        return analysisUserVo;
    }

    //统计图封装方法
    public List<Year> analysisByDay(String start, String end, String type) {

        System.err.println(type);
        //创建返回的集合
        List<Year> yearList = new ArrayList<>();

        //查找条件
        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("record_date", start, end);
        //在数据库中查找
        List<AnalysisByDay> analysisByDays = analysisByDayMapper.selectList(queryWrapper);
        //滤空
        if (CollectionUtil.isNotEmpty(analysisByDays)) {
            //遍历
            for (AnalysisByDay analysisByDay : analysisByDays) {
                //创建实体类
                Year year = new Year();
                //分类型
                if (StrUtil.equals(type,"101")) {
                    Date recordDate = analysisByDay.getRecordDate();
                    String format = new SimpleDateFormat("yyyy-MM-dd").format(recordDate);
                    year.setTitle(format);
                    year.setAmount(analysisByDay.getNumRegistered());
                } else if (StrUtil.equals(type,"102")) {

                    Date recordDate = analysisByDay.getRecordDate();
                    String format = new SimpleDateFormat("yyyy-MM-dd").format(recordDate);
                    year.setTitle(format);
                    year.setAmount(analysisByDay.getNumActive());

                } else if (StrUtil.equals(type,"103")) {
                    Date recordDate = analysisByDay.getRecordDate();
                    String format = new SimpleDateFormat("yyyy-MM-dd").format(recordDate);
                    year.setTitle(format);
                    year.setAmount(analysisByDay.getNumRetention1d());
                }
                //放入集合
                yearList.add(year);
            }
        }
        //返回
        return yearList;
    }
}
